package com.ybkj.daijia.api.driver.v4up;

import static com.ybkj.daijia.server.model.DriverEnchashment.AMOUT;
import static com.ybkj.daijia.server.model.DriverEnchashment.HELP_PAY;

import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.api.util.ErrorConstantV4;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverEnchashment;
import com.ybkj.daijia.server.model.DriverLogin;
import com.ybkj.daijia.server.service.DriverEnchashmentService;
import com.ybkj.daijia.server.service.DriverHelppayService;
import com.ybkj.daijia.server.service.DriverLoginService;
import com.ybkj.daijia.server.service.DriverService;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller("DriverEnchashmentControllerV4up")
@RequestMapping(value = "driver/api/rest/v4up")
public class DriverEnchashmentController {

    private static final Logger logger = LoggerFactory.getLogger(DriverEnchashmentController.class);

    @Autowired
    private DriverEnchashmentService driverEnchashmentService;

    @Autowired
    private DriverService driverService;

    @Autowired
    private DriverLoginService driverLoginService;

    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private DriverHelppayService driverHelppayService;

    /**
     * 司机获取提现记录
     *
     * @param employToken
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping(value = "queryEnchashment", method = RequestMethod.GET)
    public @ResponseBody
    ResultTransport queryEnchashment(String employToken, Integer page, Integer limit) {

        logger.debug("recv employToken:{},page:{},limit:{}", employToken, page, limit);

        if (StringUtils.isBlank(employToken) || null == page || null == limit) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        try {

            Page<DriverEnchashment> enchashments = driverEnchashmentService
                .queryByEmploy(driverLogin.getDriverId(), null, page, limit);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(enchashments);

            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 driver queryEnchashment error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }

    /***
     * 司机提现
     * @record zhyu
     * @param employToken
     * @param money
     * @param bank
     * @param cardNumber
     * @param masterName 提现人
     * @param type =helppay 表示可代付余额, null或者amount表示余额
     * @return
     */
    @RequestMapping(value = "applyEnchashment", method = RequestMethod.POST)
    public synchronized @ResponseBody
    ResultTransport applyEnchashment(String employToken, BigDecimal money, String bank,
        String cardNumber, String masterName,
        @RequestParam(value = "type", required = false) String type) {
//		long now = System.currentTimeMillis();
//		long start1 = 1569859200000L;
//		long end = 1570464000000L;
//		if(now > start1 && now < end){
//			return ResultTransport.getErrorBy(ErrorConstantV4.GUO_QING);
//		}

        Calendar calendar = Calendar.getInstance();
        int a = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (a != 4 && a != 1) {
            return ResultTransport.getErrorBy(ErrorConstantV4.GUO_QING);
        }

        logger.debug("recv employToken:{},money:{},memo:{}", employToken, money);
        Setting oldsetting = settingUtils.get();
        if (money.doubleValue() % oldsetting.getMoenyBase().doubleValue() != 0
            || money.doubleValue() < oldsetting.getStartQuota().doubleValue()
            || money.doubleValue() > oldsetting.getEndQuota().doubleValue()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.MOENY_INPUT_ERROR);
        }

        if (StringUtils.isBlank(employToken) || null == money || StringUtils.isBlank(bank)
            || StringUtils.isBlank(cardNumber) || StringUtils.isBlank(masterName)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        if (money.compareTo(BigDecimal.ZERO) == 0) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin && !employToken.equals("super")) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (!employToken.equals("super") && System.currentTimeMillis() >= driverLogin.getDeathDate()
            .getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }
        Driver driver = null;
        if (employToken.equals("super")) {
            driver = driverService.findOne(30L);
        } else {
            driver = driverService.findOne(driverLogin.getDriverId());
        }
        if (!driver.canTixian()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_CANT_TIXIAN);
        }
        if (null != type && type.equals(HELP_PAY)) {
            BigDecimal helppayMoney = driverHelppayService.getHelppayMoneyById(driver.getId());
            if (-1 == helppayMoney.compareTo(money)) {
                return ResultTransport
                    .getErrorBy(ErrorConstantV4.EMPLOY_ENCHASHMENT_HELP_MONEY_NOT_ENOUGH);
            }
        }
        if (null == type || (null != type && type.equals(AMOUT))) {
            if (driver.getVirtual().compareTo(money) == -1) {
                return ResultTransport
                    .getErrorBy(ErrorConstantV4.EMPLOY_ENCHASHMENT_MONEY_NOT_ENOUGH);
            }
        }

        if (driver.getIsFreeze()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
        }

        try {

            driver.setBankName(bank);
            driver.setBankNo(cardNumber);
            driver.setSkrName(masterName);
            int result = driverService.updateByPrimaryKey(driver);

            if (result == 0) {
                return ResultTransport.getErrorBy(ErrorConstantV4.DRIVER_UPDATE_ERROR);
            }

            driverEnchashmentService
                .applyEnchashment(driver, money, bank, cardNumber, masterName, type);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 driver applyEnchashment error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

}
